<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/index.css">
    <script src="js/jquery-3.3.1.min.js"></script>
    <script src="js/template-native.js"></script>
    <script type="text/html" id="tem">
        <% for(var i = 0; i < comments.length; i++){ %>
            <li uid="<%= comments[i].id %>">
                <p class="floor"><%= comments[i].id %>楼<a href="javascript:;" class="delete">删除</a></p>
                <p class="author">层主：<%= comments[i].username %></p>
                <p class="content"><%= comments[i].content %></p>
            </li>
        <% } %>
       
    </script>
</head>
<body>
    <div class="main">
        <div class="post">
            <h3>新年快乐</h3>
            <p class="author">楼主：行痴</p>
            <p>新的一年，祝大家新年快乐，身体健康，升职加薪！</p>
        </div>
        <div class="reply">
            <h5>发表回复</h5>
            <label>用户名：</label><input type="text" class="username">
            <textarea  cols="30" rows="10" class="content"></textarea>
            <input type="button" value="发表" class="btn">
        </div>
        <div class="cmts">
            <ul class="list">
               
            </ul>
        </div>
    </div>
    <script>
        var uls = $(".main .cmts .list");
        $.ajax({
            url:"http://localhost:3000/db",
            type:"GET",
            success:function(data){
                console.log(data);
                uls.html(template("tem",data));
                // 删除数据
                deleteUrl();
            }
        })
        // 添加数据
        var user = $(".username");
        var txt = $(".content");
        var btn = $(".btn");
        btn.click(function(){
            var username = user.val();
            var content = txt.val();
            $.ajax({
                url:"http://localhost:3000/comments",
                type:"POST",
                dataType:"json",
                data:{
                    username : username,
                    content : content
                },
                success:function(data){
                    uls.append(template("tem",{"comments": [data]}));
                    deleteUrl();
                }
            });
            user.val("");
            txt.val("");
        });
        // 封装删除函数
        function deleteUrl(){
            $(".cmts .list .delete").click(function(){
                lis = $(this).parents("li");
                var index = lis.attr("uid");
                console.log(index);
                $.ajax({
                    url:"http://localhost:3000/comments/" + index,
                    type:"DELETE",
                });
                lis.remove();
            })
        }
    </script>
</body>
</html>